package com.redstar.HappyRefresh.limit;

import com.redstar.HappyRefresh.cache.UserInfo;
import com.redstar.HappyRefresh.constant.RedisConstant;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Aspect
@Component
public class LimiterAop {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Around("@annotation(limiter)")
    public Object restriction(ProceedingJoinPoint joinPoint, Limit limiter) throws Throwable {
        Long userId = UserInfo.get();
        if (userId == null) {
            throw new RuntimeException("游客登录禁止发布视频");
        }
        int limit = limiter.limit(); // 限制次数
        String msg = limiter.msg(); // 错误提示信息
        long time = limiter.time(); // 规定时间
        // 限流，key为video:limit:${userId}，value为视频操作次数
        String key = RedisConstant.VIDEO_LIMIT + userId;
        Object value = redisTemplate.opsForValue().get(key);
        if (ObjectUtils.isEmpty(value)) { // 在规定时间内对视频进行操作
            redisTemplate.opsForValue().set(key, 1L, time);
        } else {
            if (Integer.parseInt(value.toString()) > limit) { // 在规定时间内发布视频或修改视频超过限制次数
                throw new RuntimeException(msg);
            }
            redisTemplate.opsForValue().increment(key, 1L); // 视频操作次数加1
        }
        return joinPoint.proceed();
    }
}